const {User} = require('@/mysql/user')
const {ProjectType} = require('@/mysql/project_type')
/** 查找当前用户信息 */
const getPersonInfo = async ctx => {
    ctx.response.body = global.utils.PersonInfo
}
const  insertProject = async ctx => {
    if (ctx.request.body) {
        let {name, description, type_id} = ctx.request.body
        if (!name) return ctx.response.body = global.toJson(1, `缺少项目名称`)
        if (type_id) {
            const data = await ProjectType.findById(type_id);
            if(!data.length) return ctx.response.body = global.toJson(1, `没有找到该分类`)
        }
        const data = await User.addProject(name, description, type_id)
        if (data) {
            ctx.response.body = global.toJson(0, '添加项目成功')
        }
    }
}
const  updateProject = async ctx => {
    if (ctx.request.body) {
        const project_id = ctx.params.id
        if(!project_id) return ctx.body = global.toJson(1, '缺失项目Id')
        let {name, description, type_id} = ctx.request.body
        if (!name) return ctx.response.body = global.toJson(1, `缺少项目名称`)
        if (type_id) {
            const data = await ProjectType.findById(type_id);
            if(!data.length) return ctx.response.body = global.toJson(1, `没有找到该项目分类`)
        }
        const data = await User.updateProject(name, description, type_id, project_id)
        if (data) {
            ctx.response.body = global.toJson(0, '修改项目成功')
        }
    }
}
const removeProject = async ctx => {
    if(ctx.request.body) {
        const project_id = ctx.params.id
        if(!project_id) return ctx.body = global.toJson(1, '缺少删除项目Id')
        const data = await User.removeProject(project_id)
        ctx.body = global.toJson(0, '删除项目成功')
    }
}
const returnProject = async ctx => {
    if(ctx.request.body) {
        const project_id = ctx.params.id
        if(!project_id) return ctx.body = global.toJson(1, '缺少恢复项目Id')
        const data = await User.returnProject(project_id)
        ctx.body = global.toJson(0, '恢复项目成功')
    }
}
const findUser = async ctx => {
    if(ctx.request.body) {
        const {name} = ctx.request.query
        if(!name) return ctx.body = global.toJson(1, '用户名不能为空')
        const data = await User.findAll({where:{name}})
        ctx.body = data
    }
}

const updateUserInfo = async ctx => {
    const {id, name, desc, avatarImage, sex, age, phone, email, company} = ctx.request.body
    const data = await User.updateUerInfo(id,name, desc, avatarImage, sex, age, phone, email, company)
     return ctx.body = global.toJson(0, '更新用户数据成功')
}

export {getPersonInfo, insertProject,updateProject, removeProject, findUser, updateUserInfo, returnProject }
